package com.ncu.musicbox2020;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import javax.xml.datatype.Duration;

public class MainActivity extends AppCompatActivity {

    private List<MusicInfo> musicList = new ArrayList<MusicInfo>();
    private ListAdapter mlistAdapter;
    private ListView mListView;
    private ImageView btnPrevious;
    private ImageView btnNext;
    private ImageView btnPlay;
    private ImageView imagestyle;
    private TextView listTitle;
    private TextView playingName;
    private SeekBar musicSeekBar;
    private MusicMannager mManager = null;

    Intent intent_serve;
    public final int STATUS_PLAY = 0;
    public final int STATUS_NEXT = 1;
    public final int STATUS_PREV = 2;

    public int status_style = 0;//      0->表示当前的方式是顺序播放 1->表示当前的方式是单曲播放 2->表示当前的方式的随机播放
    private boolean music_playing = false;

    private Handler handler = new Handler();
    private Runnable updateThread = new Runnable() {
        @Override
        public void run() {
            if(mManager!=null){
                try {
                    if(mManager.isPlaying()){
                        int Duration = mManager.getDuration();
                        int currentPos = mManager.getCurrentPosition();
                        musicSeekBar.setMax(Duration);
                        musicSeekBar.setProgress(currentPos);
                        //将当前的进度与总进度转换为秒进行转换
                        int prg_sec = currentPos/1000;
                        int max_sec = Duration / 1000;
                        if(prg_sec==max_sec) {
                            updateState(STATUS_NEXT);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            handler.post(updateThread);
        }
    };
    public void updateMusicInfo(){
        int index = mManager.getCurrentIndex();
        mlistAdapter.setFocusItemPos(mManager.getCurrentIndex());
        String currentMusicName = musicList.get(index).getMusic_title();
        String currentArtist = musicList.get(index).getMusic_artist();
        String musicInfo =  currentArtist+"\n"+currentMusicName;
        playingName.setText(musicInfo);
    }
    private void updateState(int status) {
        Context context = getApplicationContext();
        switch(status){
            case STATUS_PLAY:{
                if(music_playing==false){
                    if(mManager.getCurrentIndex()<0){
                        mManager.setCurrentIndex(0);
                        mlistAdapter.setFocusItemPos(0);
                        mManager.Play();
                    }else{
                        mManager.setCurrentIndex(mManager.getCurrentIndex());
                        mlistAdapter.setFocusItemPos(mManager.getCurrentIndex());
                        mManager.Play();
                    }
                    mManager.Resume();
                    music_playing = true;
                    btnPlay.setImageResource(R.drawable.pause);
                    updateMusicInfo();
                    return;
                }
                if(music_playing==true){
                    mManager.Pause();
                    music_playing = false;
                    btnPlay.setImageResource(R.drawable.play);
                }
                return;
            }
            case STATUS_NEXT:{
                if(status_style==0){
                    mManager.PlayNext();
                }else if(status_style==1){
                    mManager.PlayThis();
                }else{
                    mManager.PlayRandom();
                }
                mlistAdapter.setFocusItemPos(mManager.getCurrentIndex());
                updateMusicInfo();
                if(music_playing==true){
                    btnPlay.setImageResource(R.drawable.pause);
                }else{
                    btnPlay.setImageResource(R.drawable.play);
                }
                mListView.setSelection(mManager.getCurrentIndex());
                break;
            }
            case STATUS_PREV:{
                if(status_style==0){
                    mManager.PlayPrev();
                }else if(status_style==1){
                    mManager.PlayThis();
                }else{
                    mManager.PlayRandom();
                }
                mlistAdapter.setFocusItemPos(mManager.getCurrentIndex());
                updateMusicInfo();
                if(music_playing==true){
                    btnPlay.setImageResource(R.drawable.pause);
                }else{
                    btnPlay.setImageResource(R.drawable.play);
                }
                mListView.setSelection(mManager.getCurrentIndex());
                break;
            }
            default:
                throw new IllegalStateException("错误的状态"+status);
        }
    }
    //注册系统选项菜单菜单来进行功能修改
    @Override
    public boolean  onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case R.id.menu_shunxu:{
                status_style = 0;
                imagestyle.setImageResource(R.drawable.repeat_all);
                Toast.makeText(this,"顺序循环播放",Toast.LENGTH_SHORT).show();
                break;
            }
            case R.id.menu_danqu:{
                status_style = 1;
                imagestyle.setImageResource(R.drawable.repeat_one);
                Toast.makeText(this,"单曲循环播放",Toast.LENGTH_SHORT).show();
                break;
            }
            case R.id.menu_shuiji:{
                status_style = 2;
                imagestyle.setImageResource(R.drawable.shuffle);
                Toast.makeText(this,"随机循环播放",Toast.LENGTH_SHORT).show();
                break;
            }
        }
        return true;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_DENIED){
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
                requestPermissions(
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
            }
        }
        intent_serve= new Intent(this,MusicPlayerService.class);
        listTitle = (TextView)findViewById(R.id.music_list_title);
        playingName = (TextView)findViewById(R.id.music_name);
        musicSeekBar = (SeekBar)findViewById(R.id.music_seek_bar);
        btnPrevious = (ImageView)findViewById(R.id.btn_previous);
        btnNext = (ImageView)findViewById(R.id.btn_next);
        btnPlay = (ImageView)findViewById(R.id.btn_play);
        imagestyle = (ImageView)findViewById(R.id.image_style);
        mManager = new MusicMannager(MainActivity.this);
        musicList = mManager.getMusiclist();
        String title = "本地音乐（总数："+mManager.getTotal_music()+"）";
        listTitle.setText(title);
        mlistAdapter = new ListAdapter(MainActivity.this,musicList);
        mListView = (ListView)findViewById(R.id.music_list);
        mListView.setAdapter(mlistAdapter);
        handler.post(updateThread);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mManager.setCurrentIndex(position);
                mlistAdapter.setFocusItemPos(position);
                mManager.Reset();
                music_playing = false;
                updateState(STATUS_PLAY);
            }
        });
        btnPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateState(STATUS_PREV);
            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateState(STATUS_NEXT);
            }
        });
        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateState(STATUS_PLAY);
            }
        });
        musicSeekBar.setProgress(0);
        musicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(mManager !=null){
                    try {
                        mManager.seekTo(seekBar.getProgress());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            startService(intent_serve);
            finish();
        }
        if(keyCode==KeyEvent.KEYCODE_HOME){
            stopService(intent_serve);
            finish();
        }
        return true;
    }
}
